import { useNamespace } from '@ibiz-template/vue3-util';
import { IPanelField } from '@ibiz/model-core';
import { computed, defineComponent, PropType, resolveComponent, h } from 'vue';
import { PanelFieldController } from './panel-field.controller';
import './panel-field.scss';

export const PanelField = defineComponent({
  name: 'IBizPanelField',
  props: {
    modelData: {
      type: Object as PropType<IPanelField>,
      required: true,
    },
    controller: {
      type: PanelFieldController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('panel-field');

    // 类名控制
    const classArr = computed(() => {
      const { id } = props.modelData;
      const result: Array<string | false> = [ns.b(), ns.m(id)];
      result.push(...props.controller.containerClass);
      return result;
    });

    return {
      ns,
      classArr,
    };
  },
  render() {
    // 编辑器内容
    let editor = null;
    if (this.controller.data) {
      const editorProps = {
        value: this.controller.value,
        data: this.controller.data,
        controller: this.controller.editor,
        disabled: this.controller.state.disabled,
        class: this.ns.b('content'),
        readonly: this.controller.model.editor!.readOnly,
        // onChange: this.onValueChange,
      };
      if (this.$slots.default) {
        editor = this.$slots.default(editorProps);
      } else if (this.controller.editorProvider) {
        const component = resolveComponent(
          this.controller.editorProvider.formEditor,
        );
        editor = h(component, {
          ...editorProps,
        });
      } else {
        editor = <not-supported-editor modelData={this.modelData.editor} />;
      }
    }

    return <div class={this.classArr}>{editor}</div>;
  },
});
